<template>
  <el-dialog :close-on-click-modal="false" title="Add Operator" width="680px" @open="handleOpen" @close="handleClose">
    <div>
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="dataRule"
        label-position="top"
      >
        <el-form-item :label="$t('operator.name')" prop="name">
          <el-input
            v-model="dataForm.name"
            maxlength="128"
            minlength="5"
            placeholder="Operator Name"
            show-word-limit
            clearable
            @blur="() => (dataForm.name = dataForm.name.trim())"
          />
        </el-form-item>
        <el-form-item :label="$t('operator.email')" prop="email">
          <el-input
            v-model="dataForm.email"
            maxlength="128"
            placeholder="E-mail"
            show-word-limit
            clearable
            @blur="() => (dataForm.email = dataForm.email.trim())"
          />
        </el-form-item>
        <el-form-item :label="$t('operator.levelExpirationTime')" prop="expireTime">
          <el-date-picker
            v-model="dataForm.expireTime"
            type="date"
            value-format="x"
            :placeholder="$t('operator.expireTimeTip')"
            style="width: 100%"
          />
          <span style="position: absolute; right: -24px">
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('operator.leverExpireTimeTip')"
              placement="top"
            >
              <i class="el-icon-info" />
            </el-tooltip>
          </span>
        </el-form-item>
        <el-form-item :label="$t('operator.mapType')">
          <el-select v-model="dataForm.mapType" @change="mapSelect" style="width: 100%">
            <el-option
              v-for="item in mapList"
              :key="item.mapType"
              :value="item.mapType"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('operator.mapKey')" prop="mapKey">
          <div>
            <el-radio
              v-model="radio"
              label="1"
              
              style="cursor: pointer; margin-right: 10px"
              >{{ $t('operator.defaulTag') }}</el-radio
            >
          </div>
          <div>
            <el-radio v-model="radio" label="2">
              <el-input
                v-model="dataForm.mapKey"
                placeholder="key"
                maxlength="128"
                show-word-limit
                clearable
                @blur="() => (dataForm.mapKey = dataForm.mapKey.trim())"
              />
            </el-radio>
          </div>
        </el-form-item>
        <el-form-item :label="$t('operator.country')" prop="countryCode">
          <el-select
            v-model="dataForm.countryCode"
            filterable
            :placeholder="$t('operator.country')"
            style="width: 100%"
          >
            <el-option
              v-for="item in countryData"
              :key="item.countryCode3"
              :label="$t('country_or_region.' + item.countryCode3)"
              :value="item.countryCode3"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('operator.address')" prop="address">
          <el-input
            v-model="dataForm.address"
            maxlength="128"
            show-word-limit
            clearable
            @blur="() => (dataForm.address = dataForm.address.trim())"
          />
        </el-form-item>
        <el-form-item :label="$t('operator.contactName')" prop="address">
          <el-input
            v-model="dataForm.contactName"
            maxlength="64"
            show-word-limit
            clearable
            @blur="() => (dataForm.contactName = dataForm.contactName.trim())"
          />
        </el-form-item>
        <el-form-item :label="$t('operator.mobile')" prop="mobile">
          <el-input
            v-model="dataForm.mobile"
            maxlength="16"
            placeholder="Mobile"
            show-word-limit
            clearable
            @blur="() => (dataForm.mobile = dataForm.mobile.trim())"
          />
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input
            v-model="dataForm.remark"
            maxlength="256"
            show-word-limit
            clearable
            @blur="() => (dataForm.remark = dataForm.remark.trim())"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" :loading="dataListLoading" @click="dataFormSubmit()">{{
          $t('common.confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { getCountryList, addPassOperator, getPlatCode, checkCert } from '@/api/operator'
import countryJson from '@/assets/static/country.json'
import { getMapList } from '@/utils'
import { getSystemMenuList } from '@/api/system-menu'
// import {isEmail} from '@/utils/validate'

export default {
  components: {
    
  },
  data() {
    const validatePlatcode = (rule, value, callback) => {
      if (!value || value.length < 1) {
        callback(new Error(this.$t('operator.platcode_tip')))
      } else {
        callback()
      }
    }
    const validateLevelcode = (rule, value, callback) => {
      if (!value || value.length < 1) {
        callback(new Error(this.$t('operator.levelcode_tip')))
      } else {
        callback()
      }
    }
    /* var validateEmail = (rule, value, callback) => {
      if (!isEmail(value.trim())) {
        callback(new Error(this.$t('user.emailError')))
      } else {
        callback()
      }
    } */
    /* var validateMobile = (rule, value, callback) => {
      if (!isMobile(value) && value) {
        callback(new Error(this.$t('userAddUpdate.mobileError')))
      } else {
        callback()
      }
    } */
    return {
      visible: false,
      dataListLoading: false,
      oaCustomerListVisible: false,
      showCN: false,
      clickDisabled: true,
      countryData: countryJson,
      fileList: [],
      levelList: [],
      platcodeList: [],
      issuerCn: '',
      subjectCn: '',
      dataForm: {
        username: '',
        name: '',
        contactName: '',
        email: '',
        address: '',
        gmtTime: '',
        lang: '',
        platCodes: [],
        mobile: '',
        remark: '',
        countryCode: '',
        levelCode: 'ENTERPRISE_LEVEL',
        expireTime: null,
        mapType: 'MAP_BOX',
        mapKey: '',
        oaCustomerName: '',
        oaCustomerCode: ''
      },
      // STANDARD_LEVEL
      radio: '1',
      id: null,
      cmdTypeCodeList: [],
      mapList: [],
      langList: [
        { value: 'en_US', lable: 'English' },
        { value: 'zh_CN', lable: 'Simplified Chinese' },
        { value: 'zh_HK', lable: 'Traditional Chinese' },
        { value: 'pt_BR', lable: 'Portuguese' },
        { value: 'ru_RU', lable: 'Russian' },
        { value: 'tr_TR', lable: 'Turkish' },
        { value: 'hi_IN', lable: 'Hindi' },
        { value: 'uk_UA', lable: 'Ukrainian' },
        { value: 'vi_VN', lable: 'Vietnamese' },
        { value: 'tl_PH', lable: 'Tagalog' },
        { value: 'ar_EG', lable: 'Arabic' },
        { value: 'th_TH', lable: 'Thai' }
      ],
      gmtTimeList: [
        { val: 'GMT+00:00', label: 'GMT+00:00' },
        { val: 'GMT+01:00', label: 'GMT+01:00' },
        { val: 'GMT+02:00', label: 'GMT+02:00' },
        { val: 'GMT+03:00', label: 'GMT+03:00' },
        { val: 'GMT+04:00', label: 'GMT+04:00' },
        { val: 'GMT+05:00', label: 'GMT+05:00' },
        { val: 'GMT+06:00', label: 'GMT+06:00' },
        { val: 'GMT+07:00', label: 'GMT+07:00' },
        { val: 'GMT+08:00', label: 'GMT+08:00' },
        { val: 'GMT+09:00', label: 'GMT+09:00' },
        { val: 'GMT+10:00', label: 'GMT+10:00' },
        { val: 'GMT+11:00', label: 'GMT+11:00' },
        { val: 'GMT-12:00', label: 'GMT-12:00' },
        { val: 'GMT-11:00', label: 'GMT-11:00' },
        { val: 'GMT-10:00', label: 'GMT-10:00' },
        { val: 'GMT-09:00', label: 'GMT-09:00' },
        { val: 'GMT-08:00', label: 'GMT-08:00' },
        { val: 'GMT-07:00', label: 'GMT-07:00' },
        { val: 'GMT-06:00', label: 'GMT-06:00' },
        { val: 'GMT-05:00', label: 'GMT-05:00' },
        { val: 'GMT-04:00', label: 'GMT-04:00' },
        { val: 'GMT-03:00', label: 'GMT-03:00' },
        { val: 'GMT-02:00', label: 'GMT-02:00' },
        { val: 'GMT-01:00', label: 'GMT-01:00' }
      ],
      dataRule: {
        name: [
          {
            required: true,
            message: this.$t('common.nullInputTip'),
            trigger: 'blur'
          }
        ],
        contactName: [
          {
            required: true,
            message: this.$t('common.nullInputTip'),
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: this.$t('common.nullInputTip'),
            trigger: 'blur'
          },
          {
            type: 'email',
            required: true,
            message: this.$t('common.email_format_error'),
            trigger: 'blur'
          }
        ],
        /* address: [{required: true, message: 'Address be empty', trigger: 'change'}], */
        gmtTime: [
          {
            required: true,
            message: this.$t('common.nullInputTip'),
            trigger: 'blur'
          }
        ],
        lang: [
          {
            required: true,
            message: this.$t('common.nullInputTip'),
            trigger: 'blur'
          }
        ],
        /* mobile: [{required: true, message: 'Mobile be empty', trigger: 'change'},
                  {validator: validateMobile, trigger: 'change'}], */
        countryCode: [
          {
            required: true,
            message: this.$t('common.nullInputTip'),
            trigger: 'blur'
          }
        ],
        // mapKey: [
        //   {
        //     required: true,
        //     message: this.$t('common.nullInputTip'),
        //     trigger: 'blur'
        //   }
        // ],
        platCodes: [{ required: true, trigger: 'manual', validator: validatePlatcode }],
        levelCode: [{ required: true, trigger: 'manual', validator: validateLevelcode }]
      }
    }
  },
  created() {
    this.mapList = getMapList()
    // this.levelList = this.$t('operator.level_list')
  },
  methods: {
    init() {
      getCountryList()
        .then((data) => {
          this.countryData = data
        })
        .catch((e) => {
          this.$confirmError(e)
        })
      // this.getPlatCode()
      this.getLevelInfo()
      this.visible = true
      this.clickDisabled = true
      this.dataListLoading = false
      this.showCN = false
      this.$refs.dataForm.resetFields()
    },
    getLevelInfo() {
      let params = {
        characterCode: '',
        levelCode: '',
        pageNo: 1,
        pageSize: 100
      }
      getSystemMenuList(params)
        .then((res) => {
          this.levelList = res.data
        })
        .catch((e) => {
          this.$confirmError(e)
        })
    },
    getPlatCode() {
      getPlatCode('OPERATOR')
        .then((res) => {
          this.platcodeList = res
          this.dataForm.platCodes = res
        })
        .catch((err) => {
          this.$confirmError(err)
        })
    },
    mapSelect() {
      this.dataForm.mapKey = ''
    },
    defaultKeyClick() {
      if (this.dataForm.mapType === 'MAP_BOX') {
        this.dataForm.mapKey = this.mapList[0].mapKey
      } else if (this.dataForm.mapType === 'GOOGLE') {
        this.dataForm.mapKey = this.mapList[1].mapKey
      } else if (this.dataForm.mapType === 'BAIDU') {
        this.dataForm.mapKey = this.mapList[2].mapKey
      }
    },
    dataFormSubmit() {
      console.log(this.dataForm)
      console.log('oaCustomerCode:' + this.dataForm.oaCustomerCode)
      console.log('oaCustomerName:' + this.dataForm.oaCustomerName)
      if (this.radio === '2' && this.dataForm.mapKey === '') {
        this.$confirm(this.$t('operator.map_not_null'), this.$t('page.tip'), {
          confirmButtonText: this.$t('page.confirm'),
          cancelButtonText: this.$t('page.cancel'),
          type: 'warning'
        })
        return
      }

      if (this.dataForm.name.length < 5) {
        return this.$message.error('Operator name should be no less than 5 characters.')
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.createOperatorHandle()
        }
      })
    },
    handleClose() {
      this.$emit('update:model-value', false)
    },
    handleFileChange(file, fileList) {
      this.$refs.upload.clearFiles()
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (extension !== 'crt') {
        return this.$message.warning('Only the suffix can be uploaded is crt')
      }
      if (fileList.length > 1) {
        fileList.shift()
      }
      this.fileList = fileList
    },
    handleRemove(file, fileList) {
      fileList.shift()
      this.showCN = false
    },
    handlePreview(file) {},
    handleChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.shift()
      }
      this.fileList = fileList
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (extension !== 'crt') {
        fileList.shift()
        return this.$message.warning('Only the suffix can be uploaded is crt')
      }
      console.log(this.fileList)
      const certData = new FormData()
      certData.append('file', this.fileList[0].raw)
      checkCert(certData)
        .then((res) => {
          this.showCN = true
          this.issuerCn = res.issuerCn
          this.subjectCn = res.subjectCn
          console.log(res)
        })
        .catch((data) => {
          this.$message.error(data.message)
          this.fileList = []
        })
    },
    handleV4Cert(issuerCN) {
      const h = this.$createElement
      this.$msgbox({
        title: this.$t('page.tip'),
        message: h('p', null, [
          // this.$t('operator.tipDeleteEmail', { email: email })
          h('i', { style: 'color: red' }, this.$t('operator.tip_issuer_cn', { issuerCN: issuerCN }))
        ]),
        showCancelButton: true,
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            setTimeout(() => {
              done()
              setTimeout(() => {
                instance.confirmButtonLoading = false
              }, 300)
            }, 300)
          } else {
            done()
          }
        }
      }).then((action) => {
        this.systemRegisterOperator()
      })
    },
    openOaCustomer() {
      this.oaCustomerListVisible = true
      this.$nextTick(() => {
        this.$refs.oaCustomerList.init()
      })
    },
    closeOaCustomerList(customer) {
      console.log(customer)
      this.dataForm.oaCustomerName = customer.customerName
      this.dataForm.oaCustomerCode = customer.customerCode
    },
    createOperatorHandle() {
      this.dataListLoading = true
      // FLYPASS 写死 operatorType platCodes
      const formData = {
      'operatorType': 'NORMAL',
      'username': this.dataForm.email,
      'name': this.dataForm.name,
      'contactName': this.dataForm.contactName,
      'platCodes': ['PASS'],
      'email': this.dataForm.email,
      'address': this.dataForm.address,
      'gmtTime': this.dataForm.gmtTime,
      'lang': this.dataForm.lang,
      'mobile': this.dataForm.mobile,
      'remark': this.dataForm.remark,
      'countryCode': this.dataForm.countryCode,
      'levelCode': this.dataForm.levelCode,
      'mapType': this.dataForm.mapType
      }
      if (this.radio === '1') {
        formData['isDefaultMapKey'] = true
      } else {
        formData['mapKey'] = this.dataForm.mapKey
        formData['isDefaultMapKey'] = false
      }
      if (this.dataForm.expireTime !== null) {
        formData['expireTime'] = this.dataForm.expireTime
      }
      addPassOperator(formData)
        .then((res) => {
          this.dataListLoading = false
          this.$message.success(this.$t('common.operate_success'))
          this.$emit('refreshDataList')
          this.handleClose()
        })
        .catch((data) => {
          this.dataListLoading = false
          console.log(data)
          this.$message.error(data.message)
          this.fileList = []
          this.showCN = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>

.el-divider {
  margin: 10px 0;
}
</style>
